<?php

namespace app\common\model;

use app\common\library\Auth;
use think\Model;
use think\Session;

class BaseModel extends Model
{

    protected $autoWriteTimestamp = 'datetime';

    protected $dateFormat = 'Y-m-d H:i:s';

    protected $updateTime = 'updated_at';

    protected $createTime = 'created_at';

    protected $deleteTime = 'deleted_at';

    protected static string $creator = 'creator';

    protected static string $updater = 'updater';

    public function __construct($data = [])
    {
        parent::__construct($data);
    }

    public function save($data = [], $where = [], $sequence = null)
    {
        $nickName = self::getNickName();
        if (!$this->isUpdate && !isset($data[self::$creator])) {
            $data[self::$creator] = $nickName;
        }
        if ($this->isUpdate && !isset($data[self::$updater])) {
            $data[self::$updater] = $nickName;
        }
        return parent::save($data, $where, $sequence);
    }

    public function insert(array $data = [], $replace = false, $getLastInsID = false, $sequence = null)
    {
        if (!isset($data[self::$creator])) {
            $data[self::$creator] = self::getNickName();
        }
        return parent::insert($data, $replace, $getLastInsID, $sequence);
    }

    public function insertGetId(array $data, $replace = false, $sequence = null)
    {
        if (!isset($data[self::$creator])) {
            $data[self::$creator] = self::getNickName();
        }
        return parent::insertGetId($data, $replace, $sequence);
    }

    public function insertAll(array $dataSet, $replace = false, $limit = null)
    {
        if (is_array(reset($dataSet))) {
            foreach ($dataSet as $key => $item) {
                if (!isset($item[self::$creator])) {
                    $dataSet[$key][self::$creator] = self::getNickName();
                }
            }
        }
        return parent::insertAll($dataSet, $replace, $limit);
    }

    private static function getNickName()
    {
        $nickName = '管理员[%s]';
        $user = Session::get('admin');
        if (!$user) {
            $auth = Auth::instance();
            if ($auth) {
                $user = $auth->getUser();
            }
            $nickName = '用户[%s]';
        }
        return sprintf($nickName, $user['nickname'] ?? '未知');
    }

}